package leetcode.median;

import java.util.ArrayList;
import java.util.Stack;

import leetcode.base.ListNode;

public class $445_AddTwoNumbers {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ArrayList<Integer> arr1 = new ArrayList<>();
        ArrayList<Integer> arr2 = new ArrayList<>();

        while (l1 != null) {
            arr1.add(l1.val);
            l1 = l1.next;
        }
        while (l2 != null) {
            arr2.add(l2.val);
            l2 = l2.next;
        }

        int i = arr1.size() - 1;
        int j = arr2.size() - 1;
        int level = 0;
        ListNode dummy = new ListNode(-1);
        while (i >= 0 && j >= 0) {
            int sum = arr1.get(i--) + arr2.get(j--) + level;
            if (sum > 9) {
                insert(dummy, sum % 10);
                level = sum / 10;
            } else {
                insert(dummy, sum);
                level = 0;
            }

        }
        while (i >= 0 || j >= 0 || level != 0) {
            int a1 = i >= 0 ? arr1.get(i--) : 0;
            int a2 = j >= 0 ? arr2.get(j--) : 0;
            int sum = a1 + a2 + level;
            if (sum > 9) {
                insert(dummy, sum % 10);
                level = sum / 10;
            } else {
                insert(dummy, sum);
                level = 0;
            }
        }

        return dummy.next;
    }
    public void insert(ListNode dummy, int val) {
        ListNode next = dummy.next;
        dummy.next = new ListNode(val);
        dummy.next.next = next;
    }
}
